package com.leave.web.servlet;

import com.leave.context.AppContext;
import com.leave.entity.Course;
import com.leave.entity.Student;
import com.leave.service.StudentService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器（页面控制器）
 * 注意：页面控制器是负责指特定动作处理请求的Servlet对象,一般地，
 * MIS(信息系统)的一个模块(module)包括处理CRUD等类型的动作请求。
 *   前端控制器是负责整个站点所有请求处理的（Servlet和Filter）对象，主流的MVC框架都是基于Servlet或者Filter实现
 *   典型web MVC框架的包括:基于Servlet的springMVC和基于Filter的struts2.
 * 基于Servlet实现的页面控制器都必须继承httpServlet.通常重写doGet|doPost方法。
 * 但是要注意：考虑servlet-api的版本，比如servlet2.5、servlet 6.0等,不同的tomcat支持servlet-api的版本。
 * Note:
 * 1:表示功能模块对应页面的变量，变量命名为view_[add|edit|list]
 * 2:在init()方法中实例化业务逻辑service组件
 */
@WebServlet(name = "studentServlet",urlPatterns = {"/student"})
public class StudentServlet extends BaseHttpServlet {
    private final Logger logger = LoggerFactory.getLogger(StudentServlet.class);
       private final static String STUDENT_LIST = "/WEB-INF/views/instructor/instructor_student.jsp";
       private StudentService userService;
    @Override
    public void init() throws ServletException {
        super.init();
        userService= AppContext.getBean(StudentService.class);
    }
    //3:重写doGet|doPost方法

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1：接受请求参数action以及其他页面的参数值，按照约定，动作请求action依次为input、add、delete、get、edit、list.
         String action =req.getParameter("action");
        HttpSession session = req.getSession();
         String view=ErrorPage_500;
         logger.info("request process starting"+action);
        String stuID =req.getParameter("stuID");
        String keyword = req.getParameter("keyword");
         try {
             //2:调用userService完成处理,此处switch语句的语法要求jdk1.8以上。
             switch (action) {
                 case "add":
                     Student stu =new Student();
                     //接收表单(Form)参数,并转换为实体对象的属性值
                     resolveRequestParameter(req,stu);
                     //调用service组件完成数据写入
                     boolean successA = userService.addStudent(stu);
                     if (successA) {
                         // 表单提交成功
                         req.setAttribute("successMessage", "学生信息添加成功！");
                     } else {
                         // 数据写入失败
                         req.setAttribute("errorMessage", "学生信息添加失败，请重试！");
                     }
                     //指定跳转路径
                     view = "student?action=list";
                     break;
                 case "delete":
                     boolean successD = userService.deleteStudent(stuID);
                     if (successD) {
                         // 表单提交成功
                         req.setAttribute("successMessage", "学生信息删除成功！");
                     } else {
                         // 数据写入失败
                         req.setAttribute("errorMessage", "学生信息删除失败，请重试！");
                     }
                     view = "student?action=list";
                     break;
                 case "seek":
                     try {
                         List<Map<String, Object>> stuList_01 = userService.seekStudent(keyword);
                         // 将查询结果传递给前端进行展示
                         session.setAttribute("list", stuList_01);
                         view = STUDENT_LIST;
                     } catch (SQLException e) {
                         e.printStackTrace();
                     }
                     break;
                 case "edit":
                     Student stu_1 =new Student();
                     resolveRequestParameter(req,stu_1);
                     boolean successE = userService.editStudent(stu_1);
                     if (successE) {
                         // 表单提交成功
                         req.setAttribute("successMessage", "学生信息修改成功！");
                     } else {
                         // 数据写入失败
                         req.setAttribute("errorMessage", "学生信息修改失败，请重试！");
                     }
                     view = "student?action=list";
                     break;
                 case "list":
                     //查找并显示所有用户信息列表
                     List<Student> stuList = userService.listStudent(null);
//                     System.out.println("stuList="+stuList);
                     view = STUDENT_LIST;
                     req.setAttribute("list",stuList);
                     break;
                 default:
             }
         }catch (Exception e){
             e.printStackTrace();
             req.setAttribute("message",e.getMessage());
//             System.out.println(111);
             view =ErrorPage_500;
         }
        //3:页面跳转，默认转发方式
        req.getRequestDispatcher(view).forward(req, resp);
//        super.doDispatch(req,resp,view);
    }

    /**
     * 解析request参数并转换为POJO对象
     * @param req
     */
    private void resolveRequestParameter(HttpServletRequest req, Object bean) {
        Map<String, String[]> reqParameterMap = req.getParameterMap();
//        System.out.println("reqParameterMap+" + reqParameterMap);
        Map<String, String[]> propertiesMap = new HashMap<String, String[]>();
        try {
            for (Map.Entry<String, String[]> entry : reqParameterMap.entrySet()) {
                String name = entry.getKey();
                String[] values = entry.getValue();
                // 判断 request 参数是否对应 JavaBean 对象的属性
                Class<?> propertyType = PropertyUtils.getPropertyType(bean, name);
                if (propertyType != null) {
                    propertiesMap.put(name, values);
                }
            }
            // 转换为 POJO 对象 bean 的属性值
            BeanUtils.populate(bean, propertiesMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("The property name could not be found", e);
        }
    }
}
